const express = require('express');
const path = require('path');
const smartLockRoutes = require('./routes/smartLockRoutes');
const sequelize = require('./config/database');

// 创建 Express 应用实例
const app = express();

// 设置端口
const PORT = process.env.PORT || 3001;

// 中间件配置
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 初始化数据库连接
sequelize.authenticate()
  .then(() => {
    console.log('数据库连接成功');
    // 同步数据库模型
    return sequelize.sync();
  })
  .then(() => {
    console.log('数据库模型同步成功');
  })
  .catch(err => {
    console.error('数据库连接失败:', err);
  });

// 注册路由
app.use('/', smartLockRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

module.exports = app;
